package cn.edu.sig.util;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.web.bind.annotation.RequestParam;

import cn.edu.sig.bean.CurrentPage;

public class PaginationHelper<E> {
	public CurrentPage<E> fetchPage(final JdbcTemplate jt,
			final String sqlCountRows, final String sqlFetchRows,
			final String args, final int pageNo, final int pageSize,
			final ParameterizedRowMapper<E> rowMapper) {
		// determine how many rows are available
		Object[] param1 = "".equals(args) ? null : new Object[] { args };
		final int rowCount = jt.queryForInt(sqlCountRows, param1);
		// calculate the number of pages
		int pageCount = rowCount / pageSize;
		if (rowCount > pageSize * pageCount) {
			pageCount++;
		}
		// create the page object
		final CurrentPage<E> page = new CurrentPage<E>();
		page.setPageNumber(pageNo);
		page.setPagesAvailable(pageCount);
		int pageNumber = pageNo - 1;
		int rowNumber = 0;
		if (pageNumber != 0) {
			rowNumber = pageNumber * 5 + 1;
		}
		// fetch a single page of results
		final Object param[] = "".equals(args) ? new Object[] { rowNumber,
				pageSize } : new Object[] { args, rowNumber, pageSize };
		jt.query(sqlFetchRows, param, new ResultSetExtractor<Object>() {

			public Object extractData(ResultSet rs) throws SQLException,
					DataAccessException {
				final List<E> pageItems = page.getPageItems();
				int currentRow = 0;
				while (rs.next()) {
					pageItems.add(rowMapper.mapRow(rs, currentRow));

				}
				page.setPageItems(pageItems);
				return page;
			}
		});
		return page;
	}

}
